﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace FirstFloor.Reversi.Messages
{
    /// <summary>
    /// Represents a message.
    /// </summary>
    public abstract class Message
    {
        /// <summary>
        /// The move piece message name.
        /// </summary>
        public static string MessageNameMovePiece = "move";
        public static string MessageNameRestart = "res";

        private string name;

        /// <summary>
        /// Initializes a new instance of the <see cref="Message"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        protected Message(string name)
        {
            if (name == null) {
                throw new ArgumentNullException("name");
            }
            this.name = name;
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get { return this.name; }
        }

        /// <summary>
        /// Returns a string representation of this Message instance.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("{0}_{1}", Name, GetParameters());
        }

        /// <summary>
        /// Gets the string representation of the message parameters.
        /// </summary>
        /// <returns></returns>
        protected abstract string GetParameters();

        /// <summary>
        /// Creates a message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static Message CreateMessage(string data)
        {
            if (data == null) {
                throw new ArgumentNullException("data");
            }

            try {
                int pos = data.IndexOf('_');
                if (pos != -1) {
                    string name = data.Substring(0, pos);
                    string parameters = null;
                    if (pos + 1 < data.Length)
                        parameters = data.Substring(pos + 1);

                    if (name == MessageNameMovePiece) {
                        return new MovePieceMessage(parameters);
                    }
                    else if (name == MessageNameRestart) {
                        return new RestartMessage();
                    }
                }
            }
            catch (FormatException) {}

            return null;
        }
    }
}
